#include <stdio.h>
#include <unistd.h>
#include <cstring>
#include <thread>
#include <vector>
#include <errno.h>
#include <cstring>
#include "LockGuard.hpp"

using namespace std;
int ticket = 1000; //票数量
//全局变量锁，自动解锁
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;

struct threadData
{
    threadData(int num/*, pthread_mutex_t *_lock*/)
    {
        i = num;
        //lock = _lock;
    }

    int i;
    //pthread_mutex_t *lock;
};
void *buyticket(void *num)
{
    threadData* td = static_cast<threadData*>(num);
    while (true)
    {
        //加锁
        //pthread_mutex_lock(&lock);
        {
            LockGuard mutex(&lock);
            if (ticket > 0)
            {
                usleep(1000);
                ticket--;
                printf("%d 线程买到票,剩余 %d 张\n", td->i, ticket);
                // 解锁
                // pthread_mutex_unlock(&lock);
            }
            else
            {
                // pthread_mutex_unlock(&lock);
                break;
            }
        }
        usleep(13);  //买完票不会去买下一张,延时模拟过程
    }
}

int main()
{
    vector<pthread_t> v;
    vector<threadData*> td;
    // 初始化互斥量
    //pthread_mutex_t lock;
    //pthread_mutex_init(&lock, nullptr);
    
    for (int i = 0; i < 3; i++)
    {
        td.push_back(new threadData(i/*, &lock*/));
        pthread_t tid;
        pthread_create(&tid, nullptr, buyticket, td[i]);
        v.push_back(tid);
    }

    for(auto ch : v)
    {
        pthread_join(ch, nullptr);
    }

    for(auto ch : td)
    {
        delete ch;
    }

    //pthread_mutex_destroy(&lock);
    return 0;
}